rm(list=ls())
gc()
## SURVEY RESULT TABLES
library(modelsummary)
library(dplyr)
library(tidyr)
library(stringr)
library(tibble)
library(readr)
library(gt)
library(data.table)
library(gt)
#gc()

load('results/survey-results-weights.Rdata')

# Load custom function to make regression tables from summary.felm output
source('felm-summary-table.R')

means = 
  as.data.frame(t(c("Mean Outcome", 
    round(w1DemSpExp$mean.outcome,2),
    round(w1RepSpExp$mean.outcome,2),
    round(w2DemSpExp$mean.outcome,2),
    round(w2RepSpExp$mean.outcome,2),
    round(w5DemSpExp$mean.outcome,2),
    round(w5RepSpExp$mean.outcome,2))))
  
  
vars = c('Dem Exp', 'Dem Exp * Dem', 'Rep Exp' ,'Rep Exp * Rep')
names(vars)= c('DemSpExp_nohh', 'DemSpExp_nohh:Democrat','RepSpExp_nohh','RepSpExp_nohh:Republican')
l = list(w1DemSpExp, 
         w1RepSpExp, 
         w2DemSpExp, 
         w2RepSpExp, 
         w5DemSpExp, 
         w5RepSpExp)
names(l) = c('(1)', '(2)','(3)', '(4)', '(5)', '(6)')
tab1 = felm.summary.table(summaries = l,
                          coef_map = vars, output ='gt',
                          model.names=names(l), fmt =2,
                          gof_map = c('nobs', 'r.squared', 'adj.r.squared'),
                          add_rows = means)

tab1 %>%

  # column labels
  tab_spanner(label = 'Neighbor PID', columns = 2:3) %>%
  tab_spanner(label = 'Contact: Dems', columns = 4) %>%
  tab_spanner(label = 'Contact: Reps', columns = 5) %>%
  tab_spanner(label = 'Comfort: Neighbors know Party', columns = 6:7) %>%
  
  
  as_latex()%>%
  as.character %>%
  str_replace_all('longtable','tabular')%>%
  write_file('tables/Tab2.tex')


